import { useState, useEffect } from 'react';
import { 
  Table, Button, Modal, Form, Input, Switch,
  Space, Tag, message, Image, Popconfirm 
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { worksApi } from '../../utils/api';

const { TextArea } = Input;

interface Work {
  id: number;
  title: string;
  subtitle: string;
  cover_image: string | null;
  description: string | null;
  created_at: string;
  updated_at: string;
  is_active: boolean;
  images: Array<{
    id: number;
    image_url: string;
    sort_order: number;
  }>;
}

export default function CaseManagement() {
  const [works, setWorks] = useState<Work[]>([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [currentWork, setCurrentWork] = useState<Work | null>(null);
  const [form] = Form.useForm();
  const [isEditing, setIsEditing] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [workImages, setWorkImages] = useState<Array<{ url: string; sort_order: number }>>([]);

  // 加载作品列表
  const loadWorks = async (page = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const skip = (page - 1) * pageSize;
      const data = await worksApi.getWorks({ skip, limit: pageSize });
      setWorks(data);
      // 注意：后端没有返回总数，这里假设有更多数据
      setPagination(prev => ({ ...prev, current: page, pageSize, total: data.length >= pageSize ? page * pageSize + 1 : data.length }));
    } catch (error: any) {
      message.error('加载作品失败：' + error.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadWorks();
  }, []);

  // 打开新增模态框
  const showAddModal = () => {
    setIsEditing(false);
    setCurrentWork(null);
    form.resetFields();
    setWorkImages([]);
    setIsModalVisible(true);
  };

  // 打开编辑模态框
  const showEditModal = async (record: Work) => {
    setIsEditing(true);
    setCurrentWork(record);
    try {
      const workDetail = await worksApi.getWorkDetail(record.id);
      form.setFieldsValue({
        title: workDetail.title,
        subtitle: workDetail.subtitle,
        cover_image: workDetail.cover_image,
        description: workDetail.description,
        is_active: workDetail.is_active,
      });
      setWorkImages(workDetail.images?.map((img: any) => ({
        url: img.image_url,
        sort_order: img.sort_order
      })) || []);
      setIsModalVisible(true);
    } catch (error: any) {
      message.error('加载作品详情失败：' + error.message);
    }
  };

  // 关闭模态框
  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
    setWorkImages([]);
  };

  // 提交表单（新增或编辑）
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      // 准备提交数据
      const submitData = {
        ...values,
        images: workImages.map((img, idx) => ({
          image_url: img.url,
          sort_order: img.sort_order !== undefined ? img.sort_order : idx
        }))
      };
      
      if (isEditing && currentWork) {
        // 更新作品
        await worksApi.updateWork(currentWork.id, submitData);
        message.success('作品更新成功');
      } else {
        // 创建作品
        await worksApi.createWork(submitData);
        message.success('作品创建成功');
      }
      
      setIsModalVisible(false);
      form.resetFields();
      setWorkImages([]);
      loadWorks(pagination.current, pagination.pageSize);
    } catch (error: any) {
      if (error.errorFields) {
        // 表单验证错误
        return;
      }
      message.error('操作失败：' + error.message);
    }
  };

  // 添加作品图片URL
  const addWorkImage = () => {
    setWorkImages(prev => [...prev, { url: '', sort_order: prev.length }]);
  };

  // 更新作品图片URL
  const updateWorkImage = (index: number, url: string) => {
    setWorkImages(prev => {
      const newImages = [...prev];
      newImages[index] = { ...newImages[index], url };
      return newImages;
    });
  };

  // 删除作品图片
  const removeWorkImage = (index: number) => {
    setWorkImages(prev => prev.filter((_, i) => i !== index));
  };

  // 删除作品
  const handleDelete = async (id: number) => {
    try {
      await worksApi.deleteWork(id);
      message.success('作品已删除');
      loadWorks(pagination.current, pagination.pageSize);
    } catch (error: any) {
      message.error('删除失败：' + error.message);
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '封面',
      dataIndex: 'cover_image',
      key: 'cover_image',
      width: 100,
      render: (url: string | null) => 
        url ? (
          <Image src={url} alt="cover" style={{ width: 60, height: 60, objectFit: 'cover' }} />
        ) : (
          '-'
        ),
    },
    {
      title: '标题（英文）',
      dataIndex: 'title',
      key: 'title',
      width: 200,
    },
    {
      title: '副标题（中文）',
      dataIndex: 'subtitle',
      key: 'subtitle',
      width: 150,
    },
    {
      title: '图片数量',
      dataIndex: 'images',
      key: 'images',
      width: 100,
      render: (images: any[]) => images?.length || 0,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (text: string) => new Date(text).toLocaleString('zh-CN'),
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      width: 100,
      render: (isActive: boolean) => (
        <Tag color={isActive ? 'success' : 'default'}>
          {isActive ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right' as const,
      width: 150,
      render: (_: any, record: Work) => (
        <Space size="small">
          <Button 
            icon={<EditOutlined />} 
            size="small" 
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确认删除"
            description="确定要删除这个作品吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <Button 
              icon={<DeleteOutlined />} 
              size="small" 
              danger
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleRefresh = () => {
    loadWorks();
  };

  return (
    <div>
      <Space direction="horizontal" style={{ marginBottom: 16 }}>
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={showAddModal}
        >
          新增作品
        </Button>
        <Button 
          type="primary" 
          // icon={<ReloadOutlined />} 
          onClick={() => handleRefresh()}
        >
          刷新
        </Button>
      </Space>

      <Table<Work> 
        columns={columns} 
        dataSource={works} 
        rowKey="id" 
        loading={loading}
        scroll={{ x: 1200 }}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
          onChange: (page, pageSize) => {
            loadWorks(page, pageSize);
          },
          onShowSizeChange: (_current, size) => {
            loadWorks(1, size);
          },
        }}
      />

      <Modal
        title={isEditing ? "编辑作品" : "新增作品"}
        open={isModalVisible}
        onCancel={handleCancel}
        onOk={handleSubmit}
        width={600}
        okText="确认"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          name="work_form"
        >
          <Form.Item
            name="title"
            label="作品标题（英文）"
            rules={[{ required: true, message: '请输入作品标题' }]}
          >
            <Input placeholder="例如：Retro literature and art" />
          </Form.Item>

          <Form.Item
            name="subtitle"
            label="作品副标题（中文）"
            rules={[{ required: true, message: '请输入作品副标题' }]}
          >
            <Input placeholder="例如：复古文艺" />
          </Form.Item>

          <Form.Item
            name="cover_image"
            label="封面图片URL"
          >
            <Input placeholder="https://example.com/image.jpg" />
          </Form.Item>

          <Form.Item
            label="作品图片URL列表"
          >
            <Space direction="vertical" style={{ width: '100%' }}>
              {workImages.map((img, index) => (
                <Space key={index} style={{ width: '100%' }} align="start">
                  <Input
                    placeholder={`图片 ${index + 1} URL`}
                    value={img.url}
                    onChange={(e) => updateWorkImage(index, e.target.value)}
                    style={{ flex: 1 }}
                  />
                  {img.url && (
                    <Image
                      src={img.url}
                      alt={`预览 ${index + 1}`}
                      style={{ width: 60, height: 60, objectFit: 'cover' }}
                      preview
                    />
                  )}
                  <Button
                    type="text"
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => removeWorkImage(index)}
                  >
                    删除
                  </Button>
                </Space>
              ))}
              <Button
                type="dashed"
                onClick={addWorkImage}
                block
                icon={<PlusOutlined />}
              >
                添加图片URL
              </Button>
            </Space>
          </Form.Item>

          <Form.Item
            name="description"
            label="作品描述"
          >
            <TextArea rows={4} placeholder="作品描述（可选）" />
          </Form.Item>

          {isEditing && (
            <Form.Item
              name="is_active"
              label="状态"
              valuePropName="checked"
            >
              <Switch checkedChildren="启用" unCheckedChildren="禁用" />
            </Form.Item>
          )}
        </Form>
      </Modal>
    </div>
  );
}